package base

import (
	"bytes"
	"net/http"
	"io/ioutil"
	"encoding/json"
	"gitee.com/dayu1985/can_api/errors"
	"crypto/tls"
)

func Cert() *http.Transport{
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	return tr
}

var Token = ""

func POST(url string, param interface{},st int64,end bool) (interface{}, error) {
	bytesData, err := json.Marshal(param)
	if err != nil {
		return nil, errors.JsonStrfyErr(err)
	}
	reader := bytes.NewReader(bytesData)
	request, err := http.NewRequest("POST", url, reader)
	if err != nil {
		return nil, errors.HttpRequestCreateErr(err)
	}
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	request.Header.Set("Authorization", Token)
	request.Header.Set("APP", "5ab3464b33fa17124cde19ad")
	client := http.Client{Transport:Cert()}

	resp, err := client.Do(request)
	if err != nil {
		return nil, errors.HttpResponseParseErr(err)
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, errors.HttpGetDataErr()
	}
	//byte数组直接转成string，优化内存
	result := new(Result)
	err = json.Unmarshal(respBytes, result)

	if end {
		state := 99999
		if err == nil{
			state = result.Code
		}else{
			panic(err)
		}

		pb,err := json.Marshal(param)
		pstr := ""
		if err == nil{
			pstr = string(pb)
		}else{
			panic(err)
		}
		APICheckAction(st,state,url,pstr,string(respBytes))
	}

	return result.Response,err
}

func Get(url string, param interface{},st int64,end bool) (interface{}, error) {
	bytesData, err := json.Marshal(param)
	if err != nil {
		return nil, errors.JsonStrfyErr(err)
	}
	reader := bytes.NewReader(bytesData)
	request, err := http.NewRequest("GET", url, reader)
	if err != nil {
		return nil, errors.HttpRequestCreateErr(err)
	}
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	request.Header.Set("Authorization", Token)
	request.Header.Set("APP", "5a9912544d4843264cb002fc")
	client := http.Client{Transport:Cert()}

	resp, err := client.Do(request)
	if err != nil {
		return nil, errors.HttpResponseParseErr(err)
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, errors.HttpGetDataErr()
	}
	//byte数组直接转成string，优化内存
	result := new(Result)
	err = json.Unmarshal(respBytes, result)
	if end {
		state := 99999
		if err == nil{
			state = result.Code
		}else{
			panic(err)
		}

		pb,err := json.Marshal(param)
		pstr := ""
		if err == nil{
			pstr = string(pb)
		}else{
			panic(err)
		}
		APICheckAction(st,state,url,pstr,string(respBytes))
	}

	return result.Response,err
}
